<template>
    <selectFromBank v-if="showItemBank">
        <template #comfirmSelect>
            <el-button type="primary" @click="comfirmSelect">确认选择</el-button>
        </template>
        <template #checkBox="{ row }">
            <el-checkbox @click="handleCheckAllChange(row)">选择</el-checkbox>
        </template>
    </selectFromBank>
    <div v-else class="outerbox">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <h3>试卷管理</h3>
                    <div class="button_group">
                        <el-button @click="backToList" type="primary" plain size="small">返回试卷列表</el-button>
                        <el-button @click="showItemBank = true" type="primary" plain size="small">从试题库选择</el-button>
                        <el-button @click="deleteItems" type="primary" plain size="small">批量删除</el-button>
                        <el-button type="primary" plain size="small">保存试卷</el-button>
                        <paperExport class="custom-component" />
                    </div>
                </div>
                <addItem @success="handleSubmitData" ref="addItemRef" />
            </template>
            <!-- v-else -->
            <!-- <img v-if="itemList.length==0" src="/public/NoData.jpg" alt=""> -->
            <div v-for="item in itemList" :key="item.id" class="card-item">
                <div class="item-content">
                    <div class="item-actions">
                        <el-button @click="editItem(item)" circle plain :icon="Edit" type="primary" size="mini"></el-button>
                        <el-button @click="deleteItem(item)" circle plain :icon="Delete" type="danger"
                            size="mini"></el-button>
                    </div>
                    <div class="item-question">
                        <el-checkbox class="item-checkbox" v-model="item.checked"></el-checkbox>
                        {{ item.questionContent }}
                    </div>
                    <div v-if="item.type === '选择题' || item.type === '多选题' || item.type === '单项选择题'" class="item-options">
                        <!-- 选项： -->
                        <ul class="item-options-list">
                            <li class="item-option" v-for="(option, index) in item.options" :key="option">
                                <!-- <p>{{ item }}</p> -->
                                <span class="item-option-circle">{{ String.fromCharCode(65 + index) }}</span>
                                <span class="item-option-value">{{ option }}</span>
                            </li>
                        </ul>
                    </div>
                    <div class="item-info">
                        <div class="item-header">
                            <!-- {{ item }} -->
                            <div class="item-score">分值：{{ item.score }}</div>
                            <div class="item-type">题型：{{ item.type }}</div>
                        </div>
                        <div class="item-answer">答案：{{ item.answer }}</div>
                        <!-- <div class="item-tags">标签：{{ item.tag }}</div> -->
                        <!-- .join(', ') -->
                        <div class="item-difficulty">难度：{{ item.difficulty }}</div>
                    </div>
                </div>
            </div>
            <template #footer>Footer content</template>
        </el-card>

        <el-card class="count-card">
            <div class="card-content">
                <div class="card-title">题型统计</div>
                <div class="count-item" v-for="(item, index) in countList" :key="index">
                    <div class="item-label">{{ item.type }}：</div>
                    <div class="item-count">{{ item.count }}个</div>
                </div>
            </div>
            <div class="selectQuesBtGroup">
                <el-button @click="GetType('choose')" type="default" :icon="Check" plain size="mini">选择题</el-button>
                <el-button @click="GetType('multiChoose')" type="default" :icon="CircleCheck" plain
                    size="mini">多选题</el-button>
                <el-button @click="GetType('fillBlank')" type="default" :icon="Grid" plain size="mini">填空题</el-button>
                <el-button @click="GetType('combining')" type="default" :icon="HelpFilled" plain size="mini">组合题</el-button>
                <el-button @click="GetType('judge')" type="default" :icon="Finished" plain size="mini">判断题</el-button>
                <el-button @click="GetType('judge')" type="default" :icon="Finished" plain size="mini">判断题</el-button>
            </div>
            <div class="add-btn" @click="addOrEditItem({})">
                <el-button type="primary" style="width: 200px;" size="large" :icon="Plus">添加问题</el-button>
            </div>

        </el-card>
    </div>
</template>

<script setup>
import addItem from '../itemBank/addItem.vue'
import selectFromBank from '@/components/selectFromBank.vue'
import { onMounted, ref } from 'vue'
import { Plus, Check, CircleCheck, Grid, HelpFilled, Finished, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus';
import { AddItemToPaper } from '@/api/paper'
const addItemRef = ref()
const showItemBank = ref(false)
const itemList = ref([
    // {
    //     id: 1,
    //     type: '多选题',
    //     score: 15,
    //     questionContent: '题目1',
    //     answer: 'BC',
    //     tag: '语文',
    //     options: ['选项A', '选项B', '选项C', '选项D'],
    //     checked: false,
    //     difficulty: '困难',
    // },
])
const selectedItems = ref([]);

const showPaperList = defineEmits(['showPaperList'])
const backToList = () => {
    showPaperList('showPaperList')
}
const props = defineProps({
    paperDetailItems: {
        type: Array,
        default: () => []
    },

})
onMounted(() => {
    itemList.value = props.paperDetailItems
    console.log("onMounted1", itemList.value);
    itemList.value.map((item, index) => {
        if (typeof itemList.value[index].options[index] === "string") {
            console.log("string");
            console.log(itemList.value[index].options[index]);
            // itemList.value[index].options[index]
            // console.log(, typeof item.options);
        } else if (typeof itemList.value[index].options[index] === "object") {
            console.log("object");
            item.options = item.options.map(option => option.content)
        }
    })
    console.log(" itemList.value", itemList.value);
})
const handleCheckAllChange = (row) => {
    row.checked = !row.checked;
    if (row.checked) {
        // 将选中的数据加入selectedItems数组
        selectedItems.value.push(row);
    } else {
        // 将取消选中的数据从selectedItems数组中移除
        const index = selectedItems.value.findIndex(item => item.id === row.id);
        if (index !== -1) {
            selectedItems.value.splice(index, 1);
        }
    }
}
// 把数据中的options从有label和content换成一个字符串数组（只有content的内容）
// 确认选择按钮
const comfirmSelect = async () => {
    showItemBank.value = false
    console.log("selectedItems.value", selectedItems.value);
    // 把数据中的options从有label和content换成一个字符串数组（只有content的内容）
    // 把数据中的options从有label和content换成一个字符串数组（只有content的内容）
    // 提取每个对象的 content 属性，并存储到 contentArr 数组（临时储存的数组）中
    const contentArr = selectedItems.value.map(item => item.options.map(option => option.content));
    // 遍历原始数组，替换 options 属性为 contentArr
    selectedItems.value.forEach((item, index) => {
        item.options = contentArr[index];
        item.checked = false;
    });
    itemList.value = selectedItems.value// 选择的数据赋值给试卷数据源
    // 把数据中的options从有label和content换成一个字符串数组（只有content的内容）
    // 把数据中的options从有label和content换成一个字符串数组（只有content的内容）

    const newArray = itemList.value.map(obj => {
        return {
            paperId: 1,
            questionId: obj.id
        }
    })
    const dataSaveToPaper = {
        data: newArray
    }
    console.log("itemList.value from BANK", itemList.value[0].options);
    console.log("dataSaveToPaper", dataSaveToPaper);

    await AddItemToPaper(dataSaveToPaper)
}
//dialog 的添加题目
//dialog 的添加题目
const handleSubmitData = (data) => {
    let newArr = data.options.map(item => item.content)
    data.options = newArr
    data.checked = false

    itemList.value.push(data)
    // 更新 countList 中对应类型题目的数量
    const typeIndex = countList.value.findIndex((item) => item.type === data.type)
    if (typeIndex >= 0) {
        countList.value[typeIndex].count++
    }
    console.log("itemList.value from dialog", itemList.value[0].options);
}
const countList = ref([
    { type: '选择题', count: 0 },
    { type: '多选题', count: 1 },
    { type: '填空题', count: 0 },
    { type: '组合题', count: 0 },
    { type: '判断题', count: 0 },
])

const addOrEditItem = (row) => {
    addItemRef.value.open(row)
}

const editItem = (item) => {
    // 打开编辑窗口，传递题目信息
    addItemRef.value.open(item)
}

const deleteItem = (item) => {
    ElMessageBox.confirm(`确定删除这道题目吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            itemList.value.splice(itemList.value.indexOf(item), 1)
        })
        .catch(() => {
        });

}

const deleteItems = () => {
    const checkedItems = itemList.value.filter((item) => item.checked)
    if (checkedItems.length === 0) {
        return
    }
    ElMessageBox.confirm(`确定删除所选题目吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            checkedItems.forEach((item) => {
                itemList.value.splice(itemList.value.indexOf(item), 1)
            })
        })
        .catch(() => {
        });

}

const GetType = (type) => {
    console.log(' type is', type)
    addItemRef.value.open()
}
</script>


<style scoped lang="scss">
.outerbox {
    display: flex;
}

.card-header {
    .button_group {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .custom-component {
            margin-left: 13px;
        }
    }
}

.box-card {
    // display: flex;
    width: 900px;
    height: 700px;
    overflow: auto;

    &::-webkit-scrollbar {
        width: 5px;
    }

    &::-webkit-scrollbar-thumb {
        background-color: #e7e9ec;
        /* 设置滚动条滑块颜色 */
        border-radius: 4px;
        /* 设置滚动条滑块圆角 */
    }

    .card-item {
        margin-bottom: 18px;
        padding: 10px;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        background-color: rgb(245, 247, 250);
        position: relative;

        .item-content {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            align-items: flex-start;
            gap: 10px;

            .item-question {
                font-size: 16px;
                font-weight: bold;
                margin-bottom: 10px;
            }

            .item-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                gap: 20px;

                .item-type {
                    font-size: 12px;
                    color: #909399;
                    border-radius: 2px;
                }
            }

            .item-answer,
            .item-tags,
            .item-option-value,
            .item-type,
            .item-score,
            .item-difficulty {
                font-size: 12px;
                margin-top: 5px;
            }

            .item-options-list {
                list-style: none;
                padding-left: 0;
                margin-top: 5px;

                .item-option {
                    display: flex;
                    align-items: center;
                    font-size: 12px;
                    margin-top: 3px;

                    .item-option-circle {
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        width: 20px;
                        height: 20px;
                        border: 1px solid #ccc;
                        border-radius: 50%;
                        margin-right: 5px;
                        color: #909399;
                    }
                }
            }

            .item-actions {
                display: flex;
                align-items: flex-start;
                gap: 10px;
                position: absolute;
                top: 10px;
                right: 10px;
            }

            .item-checkbox {
                margin-right: 10px;
            }
        }
    }
}

.count-card {
    width: 350px;
    height: 700px;
    margin-left: 20px;

    .card-content {
        padding: 10px;

        .card-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .count-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;

            .item-label {
                color: #909399;
            }

            .item-count {
                color: #333;
            }
        }


    }

    .selectQuesBtGroup {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;

        >button {
            margin: 10px;
        }
    }

    .add-btn {
        display: flex;
        justify-content: center;
        margin-top: 15px;
        cursor: pointer;
    }
}</style>